<script lang="ts" setup>
import type { SchoolApi } from '#/api/edu/base/school';

import { onMounted, ref } from 'vue';

import { confirm, Page } from '@vben/common-ui';
import { IconifyIcon } from '@vben/icons';

import { Button, Card, Tabs } from 'ant-design-vue';

import { deleteSchool, getCampusBySchoolId } from '#/api/edu/base/school';

import SchoolInfo from './info.vue';

const schoolInfoRef = ref<InstanceType<typeof SchoolInfo>>();
const activeKey = ref(''); // 默认展开基础
const campusList = ref<SchoolApi.School[]>([]);
async function getCampusList() {
  const list = await getCampusBySchoolId();
  campusList.value = list ?? [];
  if (campusList.value.length > 0 && !activeKey.value) {
    activeKey.value = campusList.value[0].id;
  }
}
function addCampus() {
  activeKey.value = '0';
  if (campusList.value.find((item) => item.id === activeKey.value)) {
    return;
  }
  campusList.value.push({
    schoolName: '新增校区',
    id: activeKey.value,
  });
}
const onEdit = async (targetKey: MouseEvent | string, action: string) => {
  if (action === 'remove') {
    const campusListFilter = campusList.value.filter(
      (item) => item.id === targetKey,
    );
    if (campusListFilter.length === 0) {
      return;
    }
    const campus = campusListFilter[0];
    // 跳出提示框确认是否删除
    confirm(`确认要删除${campus.schoolName}吗？`)
      .then(async () => {
        if (targetKey.toString() !== '0') {
          await deleteSchool(campus.id);
        }
        campusList.value = campusList.value.filter(
          (item) => item.id !== targetKey,
        );
        activeKey.value =
          campusList.value.length > 0 ? campusList.value[0].id : '';
      })
      .catch(() => {
        // 用户点击取消，无需处理
      });
  }
};
function onSuccess(id: string) {
  if (id) {
    activeKey.value = id;
  }
  getCampusList();
}
onMounted(() => {
  getCampusList();
});
</script>
<template>
  <Page auto-content-height>
    <Card>
      <Tabs
        v-model:active-key="activeKey"
        type="editable-card"
        hide-add
        @edit="onEdit"
      >
        <template #rightExtra>
          <Button type="primary" @click="addCampus">
            <IconifyIcon icon="lucide:plus" />新增校区
          </Button>
        </template>
        <Tabs.TabPane
          v-for="campus in campusList"
          :key="campus.id"
          :tab="campus.schoolName"
          :closable="true"
        >
          <SchoolInfo
            v-if="campus.id === activeKey"
            @success="onSuccess"
            ref="schoolInfoRef"
            :id="campus.id"
            :is-campus="true"
            :create-flag="campus.id === '0'"
          />
        </Tabs.TabPane>
      </Tabs>
    </Card>
  </Page>
</template>
